#include "util.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern UART_HandleTypeDef huart1;
extern UART_HandleTypeDef huart2;

int _write(int fd, char *str, int len)
{
	HAL_UART_Transmit(&huart2, (uint8_t *)str, len, 0xFFF);
	return len;
}

/**
 * @brief 从左边开始截取n个字符：
 * 
 * @param dest 
 * @param src 
 * @param n 
 * @return char* 
 */
char *strcpyLeft(char *dest, const char *src, int n)
{
	char *p = dest;
	const char *q = src;
	int len = strlen(src);

	if (n > len) {
		n = len;
	}
	while (n--)
		*(p++) = *(q++);
	*(p++) = '\0';

	return dest;
}

/**
 * @brief 从右边开始截取n个字符：
 * 
 * @param dest 
 * @param src 
 * @param n 
 * @return char* 
 */
char *strcpyRight(char *dest, const char *src, int n)
{
	char *p = dest;
	const char *q = src;
	int len = strlen(src);

	if (n > len) {
		n = len;
	}
	//int start=len-n;
	//q=q+start;
	q += len - n;
	while (n--)
		*(p++) = *(q++);
	*(p++) = '\0';
	return dest;
}

/**
 * @brief 从中间某处截取一定长度的的子字符串：
 * 
 * @param dest 
 * @param src 
 * @param start 
 * @param n 
 * @return char* 
 */
char *strcpySub(char *dest, const char *src, char start, int n)
{
	char *p = dest;
	const char *q = src;
	const char *temp = NULL;
	int len = strlen(src);

	if (start >= len || start < 0) {
		return NULL;
	}
	temp = q + start;
	if (n > strlen(temp)) { //注意这里，截取长度如果超过了src剩余的长度则只截取到src的最后，以避免内存越界；
		n = strlen(temp);
	}
	q += start;
	while (n--)
		*(p++) = *(q++);
	*(p++) = '\0';
	return dest;
}

double _strtod(char *nptr, char **endptr)
{
	int neg;
	double d = 0.0;

	//nptr = skipSpaces(nptr);
	if (*nptr == '+')
		nptr++;
	if (*nptr == '-') {
		neg = 1;
		nptr++;
	}

	while ((*nptr >= '0') && (*nptr <= '9'))
		d = (d * 10.0) + (*nptr++ - '0');
	if (*nptr == '.') {
		double cv = 1.0;
		nptr++;
		while ((*nptr >= '0') && (*nptr <= '9')) {
			cv *= 0.1;
			d = d + (cv * (*nptr++ - '0'));
		}
	}

	/*    
    if ((*nptr == 'e') || (*nptr == 'E')) {
        int expn = 0, negexpn;
        nptr++;
        if (*nptr=='+') nptr++;
        if (negexpn=(*nptr=='-')) nptr++;
        while ((*nptr >= '0') && (*nptr <= '9')) 
            expn = fastmul10(expn)+(*nptr++ - '0');
        d *= powint(10,negexpn ? -expn : expn);
    }
*/

	if (neg)
		d = -d;
	if (endptr)
		*endptr = nptr;
	return d;
}